package com.yuan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.exception.Assert;
import com.yuan.mapper.AdminMapper;
import com.yuan.mapper.UserInfoMapper;
import com.yuan.mapper.UserLoginRecordMapper;
import com.yuan.pojo.entity.Admin;
import com.yuan.pojo.entity.UserInfo;
import com.yuan.pojo.entity.UserLoginRecord;
import com.yuan.pojo.vo.UserInfoVO;
import com.yuan.result.ResponseEnum;
import com.yuan.service.AdminService;
import com.yuan.service.UserInfoService;
import com.yuan.util.JwtUtils;
import com.yuan.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

@Service
public class AdminServiceImpl  extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private UserLoginRecordMapper userLoginRecordMapper;


    @Transactional( rollbackFor = {Exception.class})
    @Override
    public Admin login(Admin admin, String ip) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        // 用户是否存在
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        Admin adminInfo = adminMapper.selectOne(queryWrapper);
        //用户不存在
        //LOGIN_MOBILE_ERROR(-208, "用户不存在"),
        Assert.notNull(adminInfo, ResponseEnum.LOGIN_MOBILE_ERROR);


        //校验密码
        //LOGIN_PASSWORD_ERROR(-209, "密码不正确"),
        Assert.equals(MD5.encrypt(password), adminInfo.getPassword(), ResponseEnum.LOGIN_PASSWORD_ERROR);

        // 记录登录日志
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setIp(ip);
        userLoginRecord.setUserId(adminInfo.getId());
        userLoginRecordMapper.insert(userLoginRecord);

        //生成token
        String token = JwtUtils.createToken(adminInfo.getId(), adminInfo.getUsername());

        adminInfo.setPassword(token);
        return adminInfo;

    }
}
